<template>
  <div class="manage">
    <div class="manage-header">
       <el-button type="primary" @click="showAddForm">新增用户</el-button>
      <el-form :inline="true" :model="biaoGe">
        <el-form-item class="Xm">
          <el-input v-model="biaoGe.keyword" placeholder="请输入姓名" />
        </el-form-item>
        <el-button class="Xm" type="success" @click="onSubmit">查询</el-button>
      </el-form>
    </div>
    <div class="manage">
      <el-table v-model="tableData" :data="tableData" stripe style="width: 100%" :max-height="400">
        <!-- 表格列定义 -->
        <el-table-column prop="account" label="用户名" width="180" />
        <el-table-column prop="status" label="状态" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.status == 0 ? '关闭' : '启用' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="avatar" label="头像" width="180">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" width="90">
          </template>
        </el-table-column> -->
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column prop="created_at" label="时间">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.created_at) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="更新时间">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.updated_at) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)">修改</el-button>

            <!-- <el-button type="danger" size="mini" @click="handpassword(scope.row)">删除</el-button> -->

            <el-dialog width="50%" title="修改信息" :visible.sync="dialogVisible" :before-close="handleClose">
              <!-- 修改表单项定义 -->
              <div class="form-container">
                <el-form ref="form" :model="formData" :inline="true" label-width="90px">
                  <el-form-item label="用户名">
                    <el-input v-model="formData.account" />
                  </el-form-item>
                  <div style="margin: 1px 0" />
                  <el-form-item label="密码">
                    <el-input v-model="formData.password" />
                  </el-form-item>
                  <div style="margin: 1px 0" />
                  <el-form-item label="手机号">
                    <el-input v-model="formData.mobile" />
                  </el-form-item>
                  <div style="margin: 1px 0" />
                  <el-form-item label="姓名">
                    <el-input v-model="formData.username" />
                  </el-form-item>
                  <div style="margin: 1px 0" />
                  <el-form-item label="状态" prop="status">
                    <el-radio v-model="formData.status" :label="0">关闭</el-radio>
                    <el-radio v-model="formData.status" :label="1">启用</el-radio>
                  </el-form-item>
                  <div style="margin: 1px 0" />
                  <!-- <el-form-item label="头像">
                    <el-upload class="avatar-uploader" :headers="{ Authorization: token }" :action="uploadUrl" :show-file-list="false" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :on-error="handleAvatarError" list-type="picture-card">
                      <img v-if="formData.avatar" :src="formData.avatar" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon" />
                    </el-upload>
                  </el-form-item> -->
                </el-form>
              </div>
              <div slot="footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSave">保存</el-button>
              </div>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog width="50%" title="新增新信息" :visible.sync="addVisible" :append-to-body="true" :before-close="handleClose">
        <el-form ref="addFormData" :model="addFormData" :inline="true" :rules="rules" label-width="100px">
          <!-- 新增表单项定义 -->
          <el-form-item label="用户名" prop="account">
            <el-input v-model="addFormData.account" />
          </el-form-item>
          <div style="margin: 1px 0" />
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addFormData.mobile" />
          </el-form-item>
          <div style="margin: 1px 0" />
          <el-form-item label="密码" prop="password">
            <el-input v-model="addFormData.password" />
          </el-form-item>
          <div style="margin: 1px 0" />
          <el-form-item label="姓名" prop="username">
            <el-input v-model="addFormData.username" />
          </el-form-item>
          <div style="margin: 1px 0" />
          <el-form-item label="状态" prop="status">
            <el-radio v-model="addFormData.status" :label="0">关闭</el-radio>
            <el-radio v-model="addFormData.status" :label="1">启用</el-radio>
          </el-form-item>
          <div style="margin: 1px 0" />
          <!-- <el-form-item label="头像" prop="avatar">
            <el-upload class="avatar-uploader" :headers="{ Authorization: token }" :action="uploadUrl" :show-file-list="false" :before-upload="beforeAxinzheng" :on-success="beforeAxinzhe" :on-error="beforeAxinz" list-type="picture-card">
              <img v-if="addFormData.avatar" :src="addFormData.avatar" class="avatar">
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item> -->
        </el-form>
        <div slot="footer">
          <el-button @click="onel">取消</el-button>
          <el-button type="primary" @click="submitForm('addFormData')">保存</el-button>
        </div>
      </el-dialog>

      <div />
    </div>
    <div class="pager">
      <el-pagination layout="total,sizes,prev, pager, next,jumper" :total="total" :page-sizes="[10, 20, 30, 50, 100]" :page-size="biaoGe.limit" :current-page="biaoGe.page" class="custom-pagination" @current-change="handlePage" @size-change="uoludePage" />
    </div>
  </div>
</template>
<script>
import { postUser, postUsser, updataUser } from '@/api/Userad'
// import { postUsser, postUser, updataUser, postScer } from '../api/Mall'
import Cookies from 'js-cookie'
export default {
  data() {
    return {
      rules: {
        account: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        username: [{ required: true, message: '请输入姓名' }],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
        avatar: [{ required: true, message: '请上传头像' }]
      },
      status: '',
      id: '',
      label: '',
      uploadUrl: '/asd_wqdc_api/admin/file/upload', // 上传接口的 URL
      dialogVisible: false, // 修改
      addVisible: false, // 新增
      currentIndex: -1, // 初始化时没有选中任何行
      token: Cookies.get('token'),
      total: 0, // 当前的总条数
      formData: {
        account: '',
        mobile: '',
        password: '',
        username: '',
        status: '',
        avatar: ''
      },
      addFormData: {
        account: '',
        mobile: '',
        password: '',
        username: '',
        status: '',
        avatar: ''
      },
      tableData: [],
      biaoGe: {
        page: 1,
        limit: 10,
        keyword: ''
      },
      userForm: {
        // 搜索
        keyword: ''
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    handleEdit(row) {
      this.dialogVisible = true

      this.currentIndex = this.tableData.indexOf(row) // 获取该行的索引
      this.formData = Object.assign({}, row) // 使用 Object.assign 复制该行的属性（避免直接引用）

      // 获取 status 的值并设置到表单中
      //  const statusFormItem = this.$refs.statusFormItem;
      // if (statusFormItem) {
      //   this.formData.status = statusFormItem.currentValue;
      // }
    },
    formatDate(timestamp) {
      if (timestamp) {
        const date = new Date(timestamp)
        return date
          .toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          })
          .replace(/\//g, '-')
      }

      return ''
    },
    // 取消重置表格数据
    onel() {
      this.$refs.addFormData.resetFields()
      this.addVisible = false
    },
    uoludePage(newPage) {
      // 更新 limit 的值
      this.biaoGe.limit = newPage

      // 重新加载数据
      this.getList()
      console.log(newPage, 'newPage')
    },
    // 选择页码的回调函数
    handlePage(val) {
      this.biaoGe.page = val
      this.getList()
      console.log(val, 'val')
    },
    // 新增按钮
    showAddForm() {
      this.addVisible = true
    },
    // 表单校验 ，新增保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!')
          this.handleAddSave()
        } else {
          this.$message.error('请填写完整表单数据！')

          return false
        }
      })
    },
    // 新增保存
    handleAddSave() {
      postUser(this.addFormData)
        .then((data) => {
          this.$message.success(data.data.message)
          console.log(data, 'data11111111111')
          // 在请求成功后再去获取列表数据
          this.getList()
        })
        .catch((error) => {
          console.error(error)
        })
      // ...
      this.onel()
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    // 修改保存
    handleSave() {
      this.tableData.splice(this.currentIndex, 1, this.formData) // 使用该行的索引替换表格中的原始数据
      updataUser(this.formData)
        .then((data) => {
          this.$message.success(data.data.message)
          console.log(data.data.data, 'data11111111111')
        })
        .catch((error) => {
          console.error(error)
        })
      // this.getList();
      // ...
      this.dialogVisible = false
    },
    // 列表的查询
    onSubmit(pageData) {
      pageData.page = 1
      pageData.limit = 10
      this.getList(pageData)
    },

    // 修改上传图片
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      return isJPG || (isPNG && isLt2M)
    },
    handleAvatarSuccess(response, file) {
      console.log(response, 'response')
      console.log(file, 'file')
      const { data } = response // 获取服务端返回的头像 URL
      const baseUrl = 'https://worker-1252745600.cos.ap-beijing.myqcloud.com/16975354959389.png/' // 去掉固定的 URL 部分
      const imgUrl = data.replace(baseUrl, 'https://worker-1252745600.cos.ap-beijing.myqcloud.com/', '') // 去掉固定部分的 URL，并添加新的URL
      this.formData.avatar = imgUrl // 设置修改后的图片 URL
      this.$message.success('头像上传成功！')
    },
    handleAvatarError() {
      this.$message.error('头像上传失败！')
    },
    // 新增上传图片
    beforeAxinzheng(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      return isJPG || (isPNG && isLt2M)
    },
    beforeAxinzhe(response, file) {
      console.log(response, 'response')
      console.log(file, 'file')
      const { data } = response // 获取服务端返回的头像 URL
      const baseUrl = 'https://worker-1252745600.cos.ap-beijing.myqcloud.com/16975354959389.png/' // 去掉固定的 URL 部分
      const imgUrl = data.replace(baseUrl, 'https://worker-1252745600.cos.ap-beijing.myqcloud.com/', '') // 去掉固定部分的 URL，并添加新的URL
      this.addFormData.avatar = imgUrl // 设置修改后的图片 URL
      this.$message.success('头像上传成功！')
    },
    beforeAxinz() {
      this.$message.error('头像上传失败！')
    },
    getList() {
      // 发送获取列表数据的请求
      console.log(this.biaoGe, 'biaoGe')
      postUsser(this.biaoGe)
        .then((data) => {
          console.log(data.data.list, 'data11111111111')
          this.tableData = data.data.list
          this.total = data.data.count || 0
          // this.handlePage(this.biaoGe.page)
          // this.tableData.push(data.data)
          console.log(this.tableData, 'data22222222222')
        })
        .catch((error) => {
          console.error(error)
        })
    }
  }
}
</script>
<style scoped>
.el-upload img {
  width: 100%;
  height: 100%;
}
.pager {
  position: absolute;
  bottom: 50px;
  right: 100px;
}
.custom-input {
  width: 700px; /* 设置宽度 */
}
.manage {
  height: 90%;
  /* margin-left: 20px;
  margin-right: 20px; */
}
.manage-header {
  margin-top: 10px;
  margin-left: 20px;
  margin-right: 20px;
}
.manage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-container {
  height: 400px; /* 设置合适的高度 */
  overflow-y: auto; /* 显示垂直滚动条 */
}
</style>
